package com.zhenyi.youqu.admin.index;

import java.util.Date;

import org.joda.time.DateTime;

import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.utils.AuthUtils;
import com.utils.DateUtils;
import com.utils.PathUtils;
import com.youqu.common.model.YqApp;
import com.youqu.common.model.YqShopUser;
import com.zhenyi.core.VueUtils;
import com.zhenyi.youqu.core.YQController;
import com.zhenyi.youqu.interceptor.AuthInterceptor;
import com.zhenyi.youqu.interceptor.PermissionInterceptor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;

@Before({ AuthInterceptor.class, PermissionInterceptor.class })
public class YQAdminController extends YQController {

	/**
	 * 获取登录商户
	 * 
	 * @return
	 * @Time 2019年3月5日 上午12:04:39
	 */
	public YqShopUser getShopUser() {
		String uid = AuthUtils.getTokenUid(this);
		return YqShopUser.dao.findById(uid);
	}

	/**
	 * 获取登录商户权限
	 * 
	 * @return
	 * @Time 2019年3月5日 上午12:04:49
	 */
	protected Integer getShopUserRole() {
		return getShopUser().getRole();
	}

	@Override
	public void setItems(Object items) {
		setAttr("items", JsonKit.toJson(items));
	}

	protected void setData(String name, Object info) {
		if (info == null) {
			return;
		}
		String json = VueUtils.getVueData(info);
		setAttr(name, json);
	}

	protected void setData(Object info) {
		setData("data", info);
		// setAttr("data", JsonKit.toJson(info));
		// setAttr("data", JSONUtil.toJsonStr(info));
		// String json = JsonUtils.toJson(info);
		// setAttr("data", json);
	}

	protected Date getStartTime() {
		String time = getPara("startTime");
		if (StrKit.notBlank(time)) {
			setAttr("startTime", time);
			return DateUtil.parse(time, DateUtils.YYYYMMDD_HHMMSS);
		}
		String dt = DateUtil.format(new DateTime().minusDays(7).toDate(), DateUtils.YYYYMMDD) + " 00:00:00";
		setAttr("startTime", dt);
		return DateUtil.parse(dt, DateUtils.YYYYMMDD_HHMMSS);
	}

	protected Date getEndTime() {
		String time = getPara("endTime");
		if (StrKit.notBlank(time)) {
			setAttr("endTime", time);
			return DateUtil.parse(time, DateUtils.YYYYMMDD_HHMMSS);
		}
		String dt = DateUtil.today() + " 23:59:59";
		setAttr("endTime", dt);
		return DateUtil.parse(dt, DateUtils.YYYYMMDD_HHMMSS);
	}

	/**
	 * 跳转过来的页面 referer
	 * 
	 * @Time 2018年11月24日 上午10:40:29
	 */
	protected void setReferer() {
		setAttr("referer", getRequest().getHeader("Referer"));
	}

	@Override
	public void render(String view) {
		YqShopUser user = getShopUser();
		if (user == null) {
			super.render(view);
			return;
		}
		YqApp app = YqApp.dao.findByAppId(user.getAppId());
		String code = app.getCode();
		String path = view.replace("/yq/", "yq/" + code + "/");
		String newPath = PathUtils.getFile(path);
		if (FileUtil.exist(newPath)) {
			super.render("/" + path);
		} else {
			super.render(view);
		}
	}

}
